﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SensitivityTest.model;
using SensitivityTest.BLL;
using System.Xml;
using System.Net;
using SensitivityTest.ServiceClientVersion;
using SensitivityTest.ValidProductTypeID;
using System.Net.Sockets;
using System.IO;

namespace SensitivityTest
{
    public partial class Frm_Main : Form
    {
        private ClientSoftware_VersionControl_ServiceSoapClient validVersion;
        private Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoapClient validScodeAndUpload;
        //private Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoapClient saveInfoData;
        List<TestItem_RecordInfo> listNFCheckiteminfo = new List<TestItem_RecordInfo>();
        public bool loadConfig;
        public DataTable dt = new DataTable();
        public DateTime startTime;
        public double totalTime;
        public bool result=true;
        private bool FirstTime1 = true;
        private bool FirstTime2 = true;
        MDIParent1 M = null;
        public Frm_Main(MDIParent1 m)
        {
            InitializeComponent();
            M = m;
        }
      
        BusinessManager Bm = new BusinessManager();
        /// <summary>
        /// 获取数据库产品列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_Main_Load(object sender, EventArgs e)
        {
            OpenInstrument();
            checkVersion();
            lbl_result.Text = null;
            groupBox2.Enabled = false;
            DataTable dt = SQLData.SelectConfigData("select distinct ProductTypeID  from Test_OIP3_Config order by ProductTypeID");
            
            cmb_ProductName.DisplayMember = "ProductTypeID";
            cmb_ProductName.ValueMember = "ProductTypeID";
            cmb_ProductName.DataSource = dt;
            if (FirstTime1 == true)
            { 
                this.cmb_ProductName.SelectedIndexChanged += new System.EventHandler(this.cmb_ProductName_SelectedIndexChanged);
                FirstTime1 = false;
            }
            
        }
        /// <summary>
        /// 获取产品对于版本列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_ProductName_SelectedIndexChanged(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            DataTable dt = SQLData.SelectConfigData("select Versions from Test_OIP3_Config where ProductTypeID='" + cmb_ProductName.Text.Trim() + "' and Enable=1");
             if (dt.Rows.Count == 0)
            {
                MessageBox.Show("当前产品没有可用配置版本");
                groupBox2.Enabled = false;
                this.cmb_Versions.SelectedIndexChanged -= new System.EventHandler(this.cmb_Versions_SelectedIndexChanged);
                cmb_Versions.DataSource = null;
                this.cmb_Versions.SelectedIndexChanged += new System.EventHandler(this.cmb_Versions_SelectedIndexChanged);
                return;
            }
            else
            {
                groupBox2.Enabled = true;
            }
            cmb_Versions.DisplayMember = "Versions";
            cmb_Versions.ValueMember = "Versions";
            cmb_Versions.DataSource = dt;
            
            if (FirstTime2 == true)
            { 
                this.cmb_Versions.SelectedIndexChanged += new System.EventHandler(this.cmb_Versions_SelectedIndexChanged);
                FirstTime2 = false;
            }
            
        }
        /// <summary>
        /// 读取sql配置和本地校准数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmb_Versions_SelectedIndexChanged(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
            dt = SQLData.SelectConfigData("select * from Test_OIP3_Config where ProductTypeID='" + cmb_ProductName.Text.Trim() + "' and Versions='" + cmb_Versions.Text.Trim() + "' and Enable=1");
            if (dt.Rows.Count <= 0)
            {
                MessageBox.Show("无可用配置");
                return;
            }
            string a = (string)dt.Rows[0]["ChanList"];
            string[] chanList = a.Split(',');
            for (int i = 0; i <= chanList.Length - 1; i++)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[i].Cells["Chan"].Value = chanList[i];
                dataGridView1.Rows[i].Cells["F1"].Value = dt.Rows[0]["F1"];            
                dataGridView1.Rows[i].Cells["F2"].Value = dt.Rows[0]["F2"];
                dataGridView1.Rows[i].Cells["CenterFreq"].Value = dt.Rows[0]["CenterFreq"];
                dataGridView1.Rows[i].Cells["Spec"].Value = dt.Rows[0]["Spec"];
            }
            loadConfig = true;

            string sig1Power="0";
            string sig2Power = "0";
            if (!System.IO.File.Exists("d:/OIP3校准数据/" + cmb_ProductName.SelectedValue + ".xml"))
            {
                MessageBox.Show("当前产品无校准文件");
                return;
            }
            try
            {
                FileStream fs = new FileStream("d:/OIP3校准数据/" + cmb_ProductName.SelectedValue + ".xml",FileMode.Open,FileAccess.Read,FileShare.Read);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fs);
                XmlNode root=xmlDoc.SelectSingleNode("//CalData");
                if (root != null)
                {
                    sig1Power=root.SelectSingleNode("sig1Power").InnerText;
                    sig2Power = root.SelectSingleNode("sig2Power").InnerText;
                }
                else
                {
                    MessageBox.Show("当前产品无校准数据，请先校准");
                    return;
                }
               
                for (int i = 0; i <= chanList.Length - 1; i++)
                {
                    dataGridView1.Rows[i].Cells["P1"].Value = sig1Power;
                    dataGridView1.Rows[i].Cells["P2"].Value = sig2Power;
                }
                loadConfig = true;
                fs.Close();
                groupBox2.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                loadConfig = false;
                return;
            }
            
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            //this.DialogResult = DialogResult.OK;
            M.oIP3测试ToolStripMenuItem.Enabled = true;
        }
        /// <summary>
        /// 初始化仪器连接
        /// </summary>
        private void OpenInstrument()
        {
            string ErrStr = "";
            if (!Bm.OpenSig("Sig1","Sig2", out ErrStr))                                   //连接信号源1,2(固定仪器别名)
            {
                MessageBox.Show(ErrStr);
                groupBox2.Enabled = false;
                return;
            }
            ErrStr = "";
        
            if (!Bm.OpenSpec("sa",out ErrStr))
            {
                MessageBox.Show(ErrStr);
                groupBox2.Enabled = false;
                return;
            }
           // groupBox2.Enabled = true;
        }
        /// <summary>
        /// 校准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_calibration_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count <= 1)
            {
                MessageBox.Show("配置参数为空");
                return;
            }
            Bm.StartCalibration(loadConfig, this);
            SaveSigCalData();
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            SMC100A SIG = new SMC100A();
            //if (CheckPreviousStepData() == false)                                                       //工序管控
            //{
            //    return;
            //}
            startTime = DateTime.Now;
            if (string.IsNullOrEmpty(txt_User.Text) || txt_User.TextLength!=6)
            {
                txt_User.Focus();
                txt_User.SelectAll();
                MessageBox.Show("用户名有误");
                return;
            }
            if (string.IsNullOrEmpty(txt_SN.Text))
            {
                MessageBox.Show("请先输入条码");
                return;
            }
            if (dataGridView1.Rows.Count<=0)
            {
                MessageBox.Show("请加载配置信息");
                return;
            }
            if (dataGridView1.Rows[0].Cells["P1"].Value == null || dataGridView1.Rows[0].Cells["P2"].Value == null)
            {
                MessageBox.Show("无校准数据");
                return;
            }

            Bm.StartTest(this);                                     //开始测试

            TimeSpan ts1 = new TimeSpan(startTime.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts = ts2.Subtract(ts1).Duration();
            totalTime = Convert.ToInt64(ts.TotalSeconds);                  //测试总时间
            
            //CheckProductTypeID();                                    //已经在前段添加配置的时候添加S代码校验
            //SQLData.InsertIntoData(this, out id);                    //保存记录表--存储过程
            //SQLData.InsertIntoItemData(this, id);                    //保存明细表--存储过程

            if (!saveData())
            {
                MessageBox.Show("数据上传失败");
                SIG.SetRFOff(1);
                SIG.SetRFOff(2);
                return;
            }

            if (result == true)
            {
                lbl_result.Text = "Pass";
                lbl_result.ForeColor = System.Drawing.Color.PaleTurquoise;
            }
            else
            {
                lbl_result.Text = "Fail";
                lbl_result.ForeColor = System.Drawing.Color.Red;
            }
            MessageBox.Show("测试完成");
            SIG.SetRFOff(1);
            SIG.SetRFOff(2);
        }

        private void GetLocalIP()
        {
            string NetSeg =MDIParent1.localIP.Split('.')[2];
            if(int.Parse(NetSeg)>=80 && int.Parse(NetSeg)<=89)
            {
                SQLData.mServer = "10.53.80.11";
            }
            else if (int.Parse(NetSeg) >= 60 && int.Parse(NetSeg) <= 69)
            {
                SQLData.mServer = "10.53.60.6";
            }
            else
            {
                SQLData.mServer = "10.53.20.170";
            }
        }

        public void checkVersion()
        {
            //if (SQLData.Test_IsvaildClientSoftVersion("OIP3", "V1.0") == 0)
            //{
            //    MessageBox.Show("软件版本不可用");
            //    Application.Exit();
            //}
 
            validVersion = new ClientSoftware_VersionControl_ServiceSoapClient("ClientSoftware_VersionControl_ServiceSoap", MDIParent1.ClientSoftwareAddress);
            if (!validVersion.VersionCheck("OIP3", "1.0"))
            {
                MessageBox.Show("软件版本不可用");
                this.Close();
            }
        }

        public bool CheckPreviousStepData()
        {
            validScodeAndUpload = new Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoapClient("Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoap", MDIParent1.ScodeAndUpload);      //工序数据检测
            if (!validScodeAndUpload.ProductType_Flow_HasValidSevenStep_ForOIP3(txt_SN.Text.Trim(), cmb_ProductName.Text))
            {
                MessageBox.Show("级联查询不合格，请返回上一道工序");
                return false;
            }
            return true;
        }

        public void CheckProductTypeID()
        {
            validScodeAndUpload = new Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoapClient("Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoap", MDIParent1.ScodeAndUpload);      //S代码校验
            if (!validScodeAndUpload.IsValidProductTypeID(cmb_ProductName.Text))
            {
                MessageBox.Show("S代码错误");
                return;
            }
        }

        public bool saveData()
        {
            Test_RecordInfo RecordDataInfo = new Test_RecordInfo();
            RecordDataInfo.ID = 1;
            RecordDataInfo.ProductSN = txt_SN.Text;
            RecordDataInfo.RecordTime = DateTime.Now;
            RecordDataInfo.TestPeriod = int.Parse(totalTime.ToString());
            RecordDataInfo.ProductTypeID = cmb_ProductName.Text;
            RecordDataInfo.UserID = txt_User.Text;
            RecordDataInfo.TestEquipID =MDIParent1.localIP;
            RecordDataInfo.TestProjID = cmb_Versions.Text;
            RecordDataInfo.Remark = "";
            if (lbl_result.Text == "PASS")
            {
                RecordDataInfo.Result = true;
            }
            else
            {
                RecordDataInfo.Result = false;
            }
            RecordDataInfo.TestType = "OIP3测试";

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                TestItem_RecordInfo RecordItemDataInfo = new TestItem_RecordInfo();
                RecordItemDataInfo.ID = 1;
                RecordItemDataInfo.ProductSN = txt_SN.Text;
                RecordItemDataInfo.RecordTime = DateTime.Now;
                RecordItemDataInfo.TestItemName = dataGridView1.Rows[i].Cells["Chan"].Value + "通道 OIP3 Test";
                RecordItemDataInfo.TestItemDesc = dataGridView1.Rows[i].Cells["Chan"].Value + "," + dataGridView1.Rows[i].Cells["F1"].Value + "," + dataGridView1.Rows[i].Cells["F2"].Value;
                RecordItemDataInfo.Spec = (string)dataGridView1.Rows[i].Cells["Spec"].Value;
                RecordItemDataInfo.ResValue = dataGridView1.Rows[i].Cells["testValue"].Value.ToString();
                if (lbl_result.Text == "PASS")
                {
                    RecordItemDataInfo.Result = true;
                }
                else
                {
                    RecordItemDataInfo.Result = false;   
                }
                listNFCheckiteminfo.Add(RecordItemDataInfo);
            }
            validScodeAndUpload = new Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoapClient("Test_Record_OIP3_DataUploadAndProcessControl_ServiceSoap", MDIParent1.ScodeAndUpload);     //上传数据

            if (validScodeAndUpload.OIP3Data_Upload(RecordDataInfo, listNFCheckiteminfo.ToArray()))
            {
               
            }
            else
            {
                return false;
            }
            return true;
        }

        private void txt_Offset_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8) && (e.KeyChar != 46))
            {
                e.Handled = true;
                base.OnKeyPress(e);
                this.txt_Offset.Text = "";
            }
        }
        public void SaveSigCalData()
        {
            if (!System.IO.Directory.Exists("d:/OIP3校准数据"))
            {
                System.IO.Directory.CreateDirectory("d:/OIP3校准数据");
            }
            string productName = this.cmb_ProductName.Text + ".xml";
            //if (!System.IO.File.Exists(productName))
            //{
            //    System.IO.File.Create("d:/OIP3校准数据/" + productName);
            //}
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
                XmlElement CalData = xmlDoc.CreateElement("CalData");
                xmlDoc.AppendChild(CalData);
                XmlElement sig1Freq = xmlDoc.CreateElement("sig1Freq");
                XmlElement sig1Power = xmlDoc.CreateElement("sig1Power");
                XmlElement sig2Freq = xmlDoc.CreateElement("sig2Freq");
                XmlElement sig2Power = xmlDoc.CreateElement("sig2Power");
                
                    sig1Freq.InnerText = (string)this.dt.Rows[0]["F1"];
                    sig1Power.InnerText = Bm.value1.ToString();
                    sig2Freq.InnerText = (string)this.dt.Rows[0]["F2"];
                    sig2Power.InnerText = Bm.value2.ToString();
             
                CalData.AppendChild(sig1Freq);
                CalData.AppendChild(sig1Power);
                CalData.AppendChild(sig2Freq);
                CalData.AppendChild(sig2Power);
                xmlDoc.Save("d:/OIP3校准数据/" + productName);
                MessageBox.Show("校准完成");
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
        }

  
    }
}
